/*
 * @Autor: xgq
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-11 17:50:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-05-23 11:42:09
 */
var express = require('express');
var category_router = express.Router();
var db = require('../../models');
const Op = require('sequelize').Op;
var comm = require('../../comm')

/**
 * @author: xgq
 * @description: 获取分类列表
 * @param {type} 
 * @return: 
 */
category_router.get('/category-list', async (req, res) => {
  let categorys = await db.category.getCategoryListByAdmin({ where: { "parentid": 0 } })
  let sub_list = await db.category.getCategoryListByAdmin({ where: { "parentid": { [Op.gt]: 0 } } })
  for (let r of sub_list.rows) {
    let f = categorys.rows.find(v => v.id == r.parentid)
    if (f) {
      if (f.children == undefined) {
        f.children = []
      }
      f.children.push(r)
    }
  }
  categorys.code = 200
  res.json(categorys)
})

/**
 * @author: xgq
 * @description: 通过id或name获取分类
 * @param {type} 
 * @return: 
 */
category_router.post('/findByIdorName', async (req, res) => {
  let result = await db.category.getCategoryByNameOrById(req.body.queryString)
  res.json(result)
})

/**
 * @author: xgq
 * @description: 添加分类
 * @param {type} 
 * @return: 
 */
category_router.post('/category-add', async (req, res) => {
  let result = { 'code': 500 }
  let { name, code, thumbnail, parentId, remark, en_name } = req.body
  let createRow = await db.category.create({
    'name': name,
    'code': code,
    'thumbnail': thumbnail,
    'parentid': parentId,
    'remark': remark,
    'en_name': en_name
  }, { raw: true }).then(function (task) {
    console.log("category created")
    comm.redis.hset('category', task.dataValues.id, JSON.stringify(task.dataValues))
    return task.dataValues
  }).catch(function (error) {
    console.log("insert category error", error)
    return null
  })

  if (createRow == null) {
    result['code'] = 507
    return res.json(result)
  }

  result.code = 200
  res.json(result)
})


/**
 * @author: Shihh
 * @description: 修改分类信息
 * @param {type} 
 * @return: 
 */
category_router.post('/category-edit', async (req, res) => {
  let result = { 'code': 200 }
  let { name, code, id, remark, en_name } = req.body
  let updateRow = await db.sequelize.transaction(t => {
    return db.category.update(
      { name: name, code: code, remark: remark, en_name: en_name },
      {
        'where': {
          'id': id
        },
        transaction: t
      }).then(re => {
        return db.category.findByPk(id, { raw: true, transaction: t }).then(re => {
          comm.redis.hset('category', re.id, JSON.stringify(re))
          return db.images.update({
            e_category: re.en_name
          }, {
            where: {
              category: re.id
            }
            , transaction: t
          })
        })
      })
  }).then(re => {
    console.log("category update")
    return true
  }).catch(err => {
    return false
  })
  if (updateRow) {
    res.json(result)
  } else {
    result['code'] = 507
    res.json(result)
  }
})

/**
 * @author: xgq
 * @description: 删除分类
 * @param {type} 
 * @return: 
 */
category_router.post('/category-del', async (req, res) => {
  let count = await db.images.count({
    where: {
      'category': req.body.id
    }
  })
  if (count > 0) {
    res.json({
      'code': '204',
      'msg': '已有图片关联'
    })
  } else {
    await db.category.destroy({
      where: {
        'id': req.body.id
      }
    }).then(re => {
      res.json({
        'code': '200',
        'msg': '删除成功'
      })
    }).catch(err => {
      console.log(err)
      res.json({
        'code': '500',
        'msg': '错误'
      })
    })
  }
})

module.exports = category_router
